package com.woniu.controller.operation;

import com.woniu.controller.BaseController;
import com.woniu.entity.Result;
import com.woniu.pojo.User;
import com.woniu.service.IUserService;
import com.woniu.vo.UserLoginVo;
import com.woniu.vo.UserRegisterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/users")
@Api(tags = "用户登录与登出")
public class LoginController extends BaseController {

    @Autowired
    private IUserService userService;


    @PostMapping("/login")
    @ApiOperation("登录")
    public Result login(@RequestBody UserLoginVo userLoginVo){
        //1.获取参数
        String nickname = userLoginVo.getNickname();
        String wechat = userLoginVo.getWechat();
        String avatar = userLoginVo.getAvatar();
        //2.对参数进行非空校验
        if(StringUtils.isEmpty(nickname)){
            return error();
        }
        if (StringUtils.isEmpty(wechat)){
            return error();
        }
        //3.调用方法进登录操作，也就是调用方法查询数据库是否有值
        User user=userService.searchByWechat(wechat);
        Map<String,String> map=new HashMap<>();
        //4.封装返回对象
        if(user==null){//如果没有查到这个用户，就新建一个用户
            User user1=new User();
            user1.setNickname(nickname);
            user1.setHeadImage(avatar);
            user1.setWechat(wechat);
            userService.save(user1);
            //封装返回数据
            //给前端返回一个令牌
            map.put("token",wechat);
            return toDataResult(map,"请绑定手机号");
        }
        //5.向前端响应数据
        String userWechat = user.getWechat();
        map.put("token",userWechat);
        if(user.getPhone()!=null){
            return toDataResult(map);
        }
        return toDataResult(map,"请绑定手机号");

    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterVo userRegisterVo){
        if(userRegisterVo.getId() == 0){
            return error();
        }
        if(StringUtils.isEmpty(userRegisterVo.getPhone())){
            return error();
        }
        Boolean flag=userService.insertPhone(userRegisterVo.getId(),userRegisterVo.getPhone());
        return  toResult(flag);

    }

    @ApiOperation("模拟根据令牌获取用户信息")
    @GetMapping("/info")
    public Result getInfo(String token){
        if(StringUtils.isEmpty(token)){
            return error();
        }
        User user = userService.searchByWechat(token);
        if(user==null){
            return error();
        }
        return toDataResult(user);
    }

    @ApiOperation("模拟退出")
    @PostMapping("/logout")
    public Result logout(){
        log.debug("==========进入了模拟退出的方法=====");
        return success();
    }







}
